package cc.atliberty.oa.controller;

import cc.atliberty.oa.pojo.User;
import cc.atliberty.oa.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@Controller
@WebServlet("/user/login")
public class LoginServlet extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符集
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        // 获取前端发送来的数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        // 封装到User对象中
        User user = new User(username,password);
        // 判断用户名和密码是否正确
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring.xml");
        UserService userService = applicationContext.getBean("userService", UserService.class);
        User checkedUser = userService.checkUser(user);
        if (checkedUser != null){
            // 设置session
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            // 检查是否设置了10天免登录
            String free = request.getParameter("free");
            // 设置了10天免登录
            if ("1".equals(free)){
                // 创建cookie对象存储用户名
                Cookie cookie1 = new Cookie("username", username);
                // 创建cookie对象存储密码
                Cookie cookie2 = new Cookie("password", password);
                // 设置cookie的有效时间为10天
                cookie1.setMaxAge(60 * 60 * 24 * 10);
                cookie2.setMaxAge(60 * 60 * 24 * 10);
                // 设置cookie的path
                cookie1.setPath(request.getContextPath());
                cookie2.setPath(request.getContextPath());
                // 响应给浏览器
                response.addCookie(cookie1);
                response.addCookie(cookie2);
            }
            // 不管选没选都跳转到用户列表界面
            response.sendRedirect(request.getContextPath() + "/dept/list");
        }else {
            response.sendRedirect(request.getContextPath() + "/error.jsp");
        }
    }
}
